/**
 * 文件上传 Hook
 */

import { useCallback, useState } from 'react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { showMessage } from '@/components/common/MessageTip';
// import { proofMapperAPI } from '@/api/proofMapper';
import type { PageRange } from '@/types/ProofMapper';
import { validatePageRange, splitPdfByRange } from '../utils/pdfUtils';

// 文件预处理函数
const preprocessFile = async (
  file: File,
  pageRange: PageRange,
  onProgress?: (progress: number) => void
): Promise<File> => {
  try {
    // 验证页面范围
    const validation = await validatePageRange(file, pageRange);
    if (!validation.isValid) {
      throw new Error(validation.error || '无效的页面范围');
    }

    // 更新总页数
    pageRange.totalPages = validation.totalPages;

    // 根据页面范围拆分文件
    return await splitPdfByRange(file, pageRange, onProgress);
  } catch (error) {
    console.error('文件预处理失败:', error);
    showMessage('error', error instanceof Error ? error.message : '文件预处理失败');
    throw error;
  }
};

export const useFileUpload = () => {
  const { updateFileStatus, parsePdf } = useProofMapper();
  const [uploading, setUploading] = useState(false);

  const uploadFile = useCallback(async (fileId: string, file: File, pageRange: PageRange) => {
    if (!file || !fileId) return;

    try {
      // 更新状态为预处理中
      updateFileStatus(fileId, 'uploading', 0);
      setUploading(true);

      // 预处理文件（根据页面范围拆分）
      const processedFile = await preprocessFile(file, pageRange, (progress) => {
        updateFileStatus(fileId, 'uploading', Math.round(progress * 0.5)); // 预处理占总进度的50%
      });
      // 调用后端解析（创建会话）
      updateFileStatus(fileId, 'parsing', 80);
      const ok = await parsePdf(processedFile);
      if (!ok) {
        updateFileStatus(fileId, 'error', 100);
        return false;
      }
      // 完成
      updateFileStatus(fileId, 'completed', 100);
      showMessage('success', '文件解析完成');
      return true;
    } catch (error) {
      updateFileStatus(fileId, 'error');
      showMessage('error', '文件处理失败，请重试');
      console.error('Upload error:', error);
      return false;
    } finally {
      setUploading(false);
    }
  }, [updateFileStatus]);

  return {
    uploadFile,
    uploading
  };
};
